//
//  TicketCheckVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/6/7.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit
import TZImagePickerController
import swiftScan
public enum TkPhotoType {
    // 0 为直接拍照   1 为查验后拍照  2 为  智能识别(拍照)  3 为 智能识别(相册)  4 为普通选图
    case directTakePhoto,takePhotoAfterCheck,takePhoto4Intelligent,library4Interlligent,directLibrary
}


// 发票查验工具
class TicketCheckVC: NSObject {
    
    var vc:TicketHolderController?
    var photoType:TkPhotoType = .directTakePhoto
    fileprivate lazy var photosPickerC = UIImagePickerController()
    
    func startLibrary4Interlligent() {
        self.photoType = .library4Interlligent
        let imagePickerVc = TZImagePickerController.init(maxImagesCount: 1, delegate: self)
        imagePickerVc!.allowTakePicture = false
        imagePickerVc!.allowPickingVideo = false
        vc?.present(imagePickerVc!, animated: true, completion: nil)
        
    }
    func startTakePhoto4Intelligent() {
        self.photoType = .takePhoto4Intelligent
        self.photosPickerC.sourceType = UIImagePickerController.SourceType.camera
        self.photosPickerC.delegate = self
        vc?.present(self.photosPickerC, animated: true, completion: {
        })
        //
    }
    func startDirectLibrary() {
        self.photoType = .directLibrary
        let imagePickerVc = TZImagePickerController.init(maxImagesCount: 1, delegate: self)
        imagePickerVc!.allowTakePicture = false
        imagePickerVc!.allowPickingVideo = false
        vc?.present(imagePickerVc!, animated: true, completion: nil)
    }
    func startDirectTakePhoto() {
        self.photoType = .directTakePhoto
        self.photosPickerC.sourceType = UIImagePickerController.SourceType.camera
        self.photosPickerC.delegate = self
        vc?.present(self.photosPickerC, animated: true, completion: {
        })
    }
    func choosePDF() {
        
        //        "public.image", "public.audio", "public.movie", "public.text", "public.item", "public.content", "public.source-code"
        let fileVC = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
        
        fileVC.allowsMultipleSelection = true
        
        fileVC.modalPresentationStyle = .formSheet
        fileVC.delegate = self
        if let topVC = getTopVC() {
            topVC.present_FullScreen(to: fileVC)
        }
        
    }
    func startScan() {
        //设置扫码区域参数
        var style = LBXScanViewStyle()
        style.centerUpOffset = 44
        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On
        style.photoframeLineW = 6
        style.photoframeAngleW = 24
        style.photoframeAngleH = 24
        style.isNeedShowRetangle = true
        
        style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid
        
        //使用的支付宝里面网格图片
        style.animationImage = UIImage(named: "qrcode_scan_part_net")
        let lbvc = LBXScanViewController()
        lbvc.scanResultDelegate = self
        lbvc.scanStyle = style
        vc?.navigationController?.pushViewController(lbvc, animated: true)
    }
    
}

extension TicketCheckVC:UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        
        
        // 创建调度组
        let workingGroup = DispatchGroup()
        var images = [UIImage]()
        var filems = [FileAssistModel]()
        var datas = [NSData]()
        
        for i in 0..<urls.count {
            let one = urls[i]
            
            
            one.startAccessingSecurityScopedResource()
            let fileCoordinator = NSFileCoordinator()
            let error = NSError()
            workingGroup.enter()
            fileCoordinator.coordinate(readingItemAt: one, options: [], error: nil) { (newUrl) in
                let fileName = newUrl.lastPathComponent
                
                do {
                    
                    guard fileName.contains(".pdf") || fileName.contains(".PDF") else {
                        KSToast("该功能仅支持pdf格式")
                        workingGroup.leave()
                        return
                    }
                    
                    if let image = convertPDFToImage(pdfURL: newUrl) {
                        let fileData = try NSData(contentsOf: newUrl, options: .dataReadingMapped)
                        
                        images.append(image)
                        var filem = FileAssistModel(json:"")
                        filem.fData = fileData as Data
                        filem.fName = fileName
                        
                        
                        filems.append(filem)
                        datas.append(fileData)
                        
                        one.stopAccessingSecurityScopedResource()
                        workingGroup.leave()
                    }
                    
                    
                } catch {
                    print("error")
                    
                }
                
            }
            
            
            
            
            
        }
        
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            // 多张pdf 一起智能识别
            if TicketAppear.shared.identifyType == .typeYn {
                self.intelligentIdentificationYn(imgs: images, filems: filems, tkType: .library4Interlligent)
            } else {
                self.intelligentIdentificationPdf(imgs:images,filems: filems,datas: datas,tkType:.library4Interlligent)
            }
            
          
           
            
        }
        
        
        
        
        
    }
    
    
}
extension TicketCheckVC:TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    // MARK: - 拍照后回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if picker.sourceType == .camera
        {
            UIImageWriteToSavedPhotosAlbum(info[UIImagePickerController.InfoKey.originalImage] as! UIImage , self, nil, nil)
        }
        let edit = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        
        
        if self.photoType == .takePhotoAfterCheck {  // 查验后拍照
            let tkconvc = TicketContentController.initForImgModel(tkType:.takePhotoAfterCheck,mainImages: [edit], models: [vc!.thodVM.one_X!], fCompany: vc!.thodVM.fCompany, invoiceTypeCode: "\(vc!.thodVM.invoiceTypeCode)",nameid: vc!.thodVM.idAname!) {
                self.vc!.tableView.mj_header?.beginRefreshing()
            }
            vc!.navigationController?.pushViewController(tkconvc, animated: true)
        } else if self.photoType == .takePhoto4Intelligent { // 智能识别拍照
            if TicketAppear.shared.identifyType == .typeYn {
                intelligentIdentificationYn(imgs: [edit],filems: [],tkType:.takePhoto4Intelligent)
            } else {
                intelligentIdentificationOri(img: edit,tkType:.takePhoto4Intelligent)
            }
            
            
        } else {  // 正常拍照
            let tkconvc = TicketContentController.initForImg(invoiceImage: edit, fCompany: vc!.thodVM.fCompany, invoiceTypeCode: "\(vc!.thodVM.invoiceTypeCode)",nameid: vc!.thodVM.idAname!) {
                self.vc!.tableView.mj_header?.beginRefreshing()
            }
            vc!.navigationController?.pushViewController(tkconvc, animated: true)
        }
        
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 选择图片后回调
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        
        if self.photoType == .library4Interlligent { // 智能识别的选图
            
            if TicketAppear.shared.identifyType == .typeYn {
                intelligentIdentificationYn(imgs: [photos.last!],filems: [],tkType:.library4Interlligent)
            } else {
                intelligentIdentificationOri(img: photos.last!,tkType:.library4Interlligent)
            }
        } else {
            let tkconvc = TicketContentController.initForImg(invoiceImage: photos.last!, fCompany: vc!.thodVM.fCompany, invoiceTypeCode: "\(vc!.thodVM.invoiceTypeCode)",nameid: vc!.thodVM.idAname!) {
                self.vc!.tableView.mj_header?.beginRefreshing()
            }
            self.vc!.navigationController?.pushViewController(tkconvc, animated: true)
        }
        
        
        
    }
    
}

extension TicketCheckVC:LBXScanViewControllerDelegate {
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        var api :API!
        if TicketAppear.shared.checkType == .typev1  {
            api = API.invoice(.checkInvoiceV1(qrcode: scanResult.strScanned.unwrap,f_type: "1",id_key:"",invoiceTypeCode: "\(vc!.thodVM.invoiceTypeCode)",f_buyername: "",f_org_id: vc!.thodVM.idAname!.id))
        } else {
            api = API.invoice(.checkInvoiceV4(qrcode: scanResult.strScanned.unwrap,f_type: "1",id_key:"",invoiceTypeCode: "\(vc!.thodVM.invoiceTypeCode)",f_buyername: "",f_org_id: vc!.thodVM.idAname!.id))
        }
        
        KSNetwork.shared.loadAny(api,showHud: true, successHandle: { [weak self]  (json) in
            guard let `self` = self else {
                return
            }
            guard let result = json as? [String: Any] else {
                return
            }
             
            if let object = result["info"], let code = result["code"] as? String,let msg = result["message"] as? String,let flag = result["flag"] as? String {
                if flag == TRUE {
                    if code == "00" {  // 00 为成功
                        successAc()
                    } else if code == "01" {  // 01 为未完善，不阻止，继续 （未完善信息，发票超过一年等）
                        imperfectionAc()
                    } else {   // 其他为错误
                        KSToast(msg)
                    }
                    
                    
                    func successAc() {
                        var dic:NSDictionary?
                        if let objS = object as? String {
                             dic = getDictionaryFromJSONString(jsonString: objS)
                        }
                        if let objD = object as? NSDictionary {
                            dic = objD
                        }
                        
                          
                        var contentDic:NSDictionary = [:]
                        if let dicunwrap = dic, let dicStr = dicunwrap["data"] as? String {
                           var  contentStr = base64Decoding(encodedString: dicStr)
                            contentDic = getDictionaryFromJSONString(jsonString: contentStr)
                        }
                        if let dicunwrap = dic, let dicDic = dicunwrap["data"] as? NSDictionary {
                            contentDic = dicDic
                        }
                        
                            print("大象返回数据")
                            print(contentDic)
                            self.vc!.thodVM.one_X = invoiceDicToModel(contentDic)
                            if self.vc!.thodVM.one_X!.fInvoicetypeId.unwrap == "14" { // 强行把通信费的转为 普通的
                                self.vc!.thodVM.one_X?.fInvoicetypeId = "10"
                            }
                            if self.vc!.thodVM.one_X!.resultCode == "0001" || self.vc!.thodVM.one_X!.resultCode == "1015" {  // 只有0001 才是真正的成功  1015 超过一年的发票允许保存
                                KSToast("查验成功，给发票拍照")
                                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                                    self.photoType = .takePhotoAfterCheck
                                    self.photosPickerC.sourceType = UIImagePickerController.SourceType.camera
                                    self.photosPickerC.delegate = self
                                    self.vc!.present(self.photosPickerC, animated: true, completion: {
                                    })
                                })
                            } else {
                                KSToast(self.vc!.thodVM.one_X!.resultTip ?? "error")
                            }
                         
                    }
                    func imperfectionAc() {
                        self.vc!.thodVM.one_X = TicketModel(json: JSON(object as Any))
                        self.vc!.thodVM.one_X!.fCheckstate = "0"
                        KSToast("\(msg)，先给发票拍张照")
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.2, execute: {
                            self.photoType = .takePhotoAfterCheck
                            self.photosPickerC.sourceType = UIImagePickerController.SourceType.camera
                            self.photosPickerC.delegate = self
                            self.vc!.present(self.photosPickerC, animated: true, completion: {
                            })
                        })
                    }
                    
                    
                } else {
                    KSToast(msg)
                }
            } else {
                KSToast("服务器出错，联系管理员")
            }
        }, errorHandle: {
            print("出错了")
        })
    }
}
extension TicketCheckVC {
    
    
    // 智能识别  单张 多张  走同一个   誉能
    func intelligentIdentificationYn(imgs:[UIImage],filems:[FileAssistModel],tkType:TkPhotoType) {
        
        // 创建调度组
        let workingGroup = DispatchGroup()
        var imageArr = [UIImage]()
        var modelArr = [TicketModel]()
        var assiArr = [[FileAssistModel]]()
        
        for i in 0..<imgs.count {
            
            let img = imgs[i]
            
            let newSize = UIImage.scaleImage(img, imageLength: 760)
            let newImage = UIImage.resizeImage(img, newSize: newSize)
            
            
            let api = API.invoice(.inVoiceControlInvoiceIdentifyYn(image: newImage))
            workingGroup.enter()
            KSNetwork.shared.doRequest(api) { [weak self] (data:BaseResult<YnInvoiceModel>) in
                guard let `self` = self else { return }
                if data.flag == TRUE {
                    if let infos = data.infoArrCombine {
                        guard infos.count > 0 else {
                            KSToast("未识别到发票")
                            return
                        }
                        
                        
                        var images = [UIImage]()
                        var models = [TicketModel]()
                        for item in infos {
                            
                            var model = TicketModel(json:"")
                            model.fInvoicetypeId = item.fInvoicetypeId
                            model.fInvoicecode = item.fInvoicecode
                            model.fInvoiceno = item.fInvoiceno
                            model.fVerifycode = item.fVerifycode
                            model.fDepartcity = item.fDepartcity
                            model.fArrivecity = item.fArrivecity
                            model.fTrainnumber = item.fTrainnumber
                            model.fBuyername = item.fBuyername
                            model.fBuyertaxno = item.fBuyertaxno
                            model.fSalername = item.fSalername
                            model.fSalertaxno = item.fSalertaxno
                            model.fTotalamount = item.fTotalamount
                            model.fInvoiceamount = item.fInvoiceamount

                            model.fTaxamount = item.fTaxamount
                            model.fInvoicedate = item.fInvoicedate
                            model.fTaxRate = item.fTaxRate
                            if let details = item.details {
                                if let first = details.first {
                                    var arr = [TicketDetailModel]()
                                    var det = TicketDetailModel(json:"")
                                    det.fGoodsname = first.fGoodsname
                                    arr.append(det)
                                    model.details = arr
                                }
                            }
                            
                            
                            guard let region = item.region,region.count == 4 else {
                                KSToast("发票范围有误")
                                return
                            }
                            
                            let xxx:CGFloat = CGFloat(region[0])
                            let yyy:CGFloat = CGFloat(region[1])
                            
                            let www:CGFloat = CGFloat(region[2] - region[0])
                            let hhh:CGFloat = CGFloat(region[3] - region[1])
                        
                            let ori = newImage.size
                            
                            if  let imagexxx = newImage.crop(rect:CGRect(x:xxx,y:yyy,width:www,height:hhh)) {
                                if model.fInvoicetypeId.unwrap != "" {
                                    images.append(imagexxx)
                                    models.append(model)
                                }
                            }
                        }
                        guard models.count > 0 else {
                            KSToast("图片未识别成功")
                            return
                        }
                        
                        // 修复渔美康的时候进行调整，其他项目留意返回是否一样
                        modelArr += models
                        imageArr += images
                        if filems.count > i {
                            assiArr.append([filems[i]])
                        }
                        
                        workingGroup.leave()
                        
                        
                        
//                        let vc = TicketContentController.initForImgModel(tkType:tkType,mainImages: images, models: models, fCompany: self.vc!.thodVM.fCompany, invoiceTypeCode: "\(self.vc!.thodVM.invoiceTypeCode)",nameid: self.vc!.thodVM.idAname!) {
//                            self.vc!.tableView.mj_header?.beginRefreshing()
//                        }
//                        self.vc!.navigationController?.pushViewController(vc, animated: true)
                    }
          
                } else {
                    KSToast(data.errorCombine.unwrap,duration: 2)
                }
           
            }
            
            
            
            
        }
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            
            let vc = TicketContentController.initForImgModel(tkType:tkType,mainImages: imageArr,assistfile: assiArr, models: modelArr, fCompany: self.vc!.thodVM.fCompany, invoiceTypeCode: "\(self.vc!.thodVM.invoiceTypeCode)",nameid: self.vc!.thodVM.idAname!) {
                self.vc!.tableView.mj_header?.beginRefreshing()
            }
            self.vc!.navigationController?.pushViewController(vc, animated: true)
            
        }
        

        
    }
    
    
    
    // 智能识别 pdf  支持多张
    func intelligentIdentificationPdf(imgs:[UIImage],filems:[FileAssistModel],datas:[NSData],tkType:TkPhotoType) {
        // 创建调度组
        let workingGroup = DispatchGroup()
        var imageArr = [UIImage]()
        var modelArr = [TicketModel]()
        var assiArr = [[FileAssistModel]]()
        
        for i in 0..<imgs.count {
            // 转换为Base64字符串
            let base64String = datas[i].base64EncodedString(options: [])
            workingGroup.enter()
            KSNetwork.shared.doRequest4Sj(API.invoice(.inVoiceControlInvoiceIdentifyBase64(str: base64String))) { [weak self] (data:SwResult<OCRResult>) in
                guard let `self` = self else { return }
                if data.flag == TRUE {
                    if let ocrResult = data.info_object {
                        if let erroMsg = ocrResult.errorMsg, erroMsg.count > 0 {
                            KSToast(erroMsg)
                        } else {
                            if let subMsgs = ocrResult.subMsgs {
                                
                                
                                
                                
                                var images = [UIImage]()
                                var models = [TicketModel]()
                                for item in subMsgs {
                                    
                                    
                                    
                                    var model = subMsg2TicketModel(item: item)
                                    
                                    let cutedimg = cutImage(ocrResult: ocrResult, img: imgs[i], item: item)
                                    if cutedimg.isSome {
                                        images.append(cutedimg!)
                                        models.append(model)
                                    }
                                
                                }
                                
                                guard images.count > 0 else {
                                    KSToast("未识别到发票")
                                    return
                                }
                                
                                modelArr.append(models.first!)
                                imageArr.append(images.first!)
                                assiArr.append([filems[i]])
                                workingGroup.leave()
                            }
                        }
                        
                    }
                    
                } else {
                    KSToast(data.errorCombine.unwrap,duration: 2)
                }
                
                
                
            }
        }
        
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            
            let vc = TicketContentController.initForImgModel(tkType:tkType,mainImages: imageArr,assistfile: assiArr, models: modelArr, fCompany: self.vc!.thodVM.fCompany, invoiceTypeCode: "\(self.vc!.thodVM.invoiceTypeCode)",nameid: self.vc!.thodVM.idAname!) {
                self.vc!.tableView.mj_header?.beginRefreshing()
            }
            self.vc!.navigationController?.pushViewController(vc, animated: true)
            
        }
        
        
        
    }
    // 智能识别   单张
    func intelligentIdentificationOri(img:UIImage,tkType:TkPhotoType) {
        
        
        KSNetwork.shared.doRequest4Sj(API.invoice(.inVoiceControlInvoiceIdentifyBase64(str: img.toBase64()))) { [weak self] (data:SwResult<OCRResult>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let ocrResult = data.info_object {
                    if let erroMsg = ocrResult.errorMsg, erroMsg.count > 0 {
                        KSToast(erroMsg)
                    } else {
                        if let subMsgs = ocrResult.subMsgs {
                            
                            
                            
                            var images = [UIImage]()
                            var models = [TicketModel]()
                            for item in subMsgs {
                                
                                
                                var model = subMsg2TicketModel(item: item)
                                
                                let cutedimg = cutImage(ocrResult: ocrResult, img: img, item: item)
                                if cutedimg.isSome {
                                    images.append(cutedimg!)
                                    models.append(model)
                                }
                            
                            }
                            
                            guard images.count > 0 else {
                                KSToast("未识别到发票")
                                return
                            }
                            
                            let vc = TicketContentController.initForImgModel(tkType:tkType,mainImages: images, models: models, fCompany: self.vc!.thodVM.fCompany, invoiceTypeCode: "\(self.vc!.thodVM.invoiceTypeCode)",nameid: self.vc!.thodVM.idAname!) {
                                self.vc!.tableView.mj_header?.beginRefreshing()
                            }
                            self.vc!.navigationController?.pushViewController(vc, animated: true)
                            
                        }
                    }
                    
                    
                }
                
            } else {
                KSToast(data.errorCombine.unwrap,duration: 2)
            }
            
            
            
        }
        
    }
    func cutImage(ocrResult:OCRResult,img:UIImage,item:SubMsgs) -> UIImage? {
        let xxx:CGFloat = CGFloat(item.sliceRect!.x0.doubleWrap)
        let yyy:CGFloat = CGFloat(item.sliceRect!.y0.doubleWrap)
        let www:CGFloat = CGFloat(item.sliceRect!.x2.doubleWrap - item.sliceRect!.x0.doubleWrap)
        let hhh:CGFloat = CGFloat(item.sliceRect!.y2.doubleWrap - item.sliceRect!.y0.doubleWrap)
        
        let imgSize = img.size
        
        let ratioX =  imgSize.width / CGFloat(ocrResult.orgWidth.doubleWrap)
        let ratioY =  imgSize.height / CGFloat(ocrResult.orgHeight.doubleWrap)
        
        
        if  let imagexxx = img.crop(rect:CGRect(x:xxx * ratioX,y:yyy * ratioY ,width:www * ratioX,height:hhh * ratioY)) {
            
            return imagexxx
            
        } else {
            return nil
        }
    }
    func subMsg2TicketModel(item:SubMsgs) -> TicketModel {
        var model = TicketModel(json:"")
        model.fInvoicecode = item.invoiceResult?.invoiceData?.fInvoicecode
        model.fInvoiceno = item.invoiceResult?.invoiceData?.fInvoiceno
        model.fVerifycode = item.invoiceResult?.invoiceData?.verifyCode
        model.fInvoiceamount = item.invoiceResult?.invoiceData?.moneyNoTax
        model.fDepartcity = item.invoiceResult?.invoiceData?.startStation
        model.fArrivecity = item.invoiceResult?.invoiceData?.endStation
        model.fTrainnumber = item.invoiceResult?.invoiceData?.trainNo
        model.fBuyername = item.invoiceResult?.invoiceData?.buyer
        model.fBuyertaxno = item.invoiceResult?.invoiceData?.buyerTaxno
        model.fSalername = item.invoiceResult?.invoiceData?.saler
        model.fSalertaxno = item.invoiceResult?.invoiceData?.salerTaxno
        if let details = item.invoiceResult?.invoiceData?.invoiceDetail {
            if let first = details.first {
                
                var arr = [TicketDetailModel]()
                var det = TicketDetailModel(json:"")
                det.fGoodsname = first.goodsName
                arr.append(det)
                model.details = arr
                
            }
        }
        
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日"
        
        if let date = formatter.date(from: item.invoiceResult!.invoiceData!.invoiceDate.unwrap) {
            formatter.dateFormat = "yyyy-MM-dd"
            model.fInvoicedate = formatter.string(from: date)
        }
        if !item.invoiceResult!.invoiceData!.taxiDate.unwrap.isEmpty {
            model.fInvoicedate = item.invoiceResult!.invoiceData!.taxiDate.unwrap
        }
        
        // 先接收发票金额
        if  let inMoney = item.invoiceResult?.invoiceData?.invoiceMoney,inMoney.count > 0 {
            model.fTotalamount = inMoney
        } else if let money = item.invoiceResult?.invoiceData?.capitalMoney,money.count > 0 { // 再接收大写金额
            model.fTotalamount =  "\(money.cpatialMoney2lowercase())"
        } else if let money = item.invoiceResult?.invoiceData?.trainMoney,money.count > 0 { // 再接票价
            model.fTotalamount =  money
        } else if let money = item.invoiceResult?.invoiceData?.onlyMoney,money.count > 0 { // 再接 金额 出租车用的
            model.fTotalamount = money.replacingOccurrences(of: "元", with: "")
        } else {
            model.fTotalamount = item.invoiceResult?.invoiceData?.lowercaseMoney
            
        }
        
        model.fInvoicetypeNm = dealInvoiceType(item: item)
        model.fInvoicetypeId = InvoiceType.name2code(dealInvoiceType(item: item))
        return model
    }
    // 返回     名称
    func dealInvoiceType(item:SubMsgs) -> String {
        var unwrapType = item.type.unwrap
        //智能识别发票类型转换
        if unwrapType == "增值税发票" {
            if let typeeee = item.invoiceResult?.invoiceData?.typeForAddValue {
                
                if typeeee.contains("专用") {
                    unwrapType = "增值税专用发票"
                } else if typeeee.contains("电子普通发票") {
                    unwrapType = "增值税普通发票(电子)"
                } else {
                    unwrapType = "增值税普通发票"
                }
            }
        }
        if unwrapType == "出租车发票" {
            unwrapType = "出租车票"
        }
        if unwrapType == "" {
            unwrapType = "其他"
        }
        if let titlex = item.invoiceResult?.invoiceData?.invoiceTitle {
            
            if titlex == "电子发票(增值税专用发票)"  {
                unwrapType = "全电发票(专用发票)"
            }
            if titlex == "电子发票(普通发票)"  {
                unwrapType = "全电发票(普通发票)"
            }
            if titlex == "深圳电子普通发票"  {
                unwrapType = "深圳区块链电子发票"
            }
            
            
        }
        
        return unwrapType
        
    }
    
}
import PDFKit

func convertPDFToImage(pdfURL: URL) -> UIImage? {
    // 创建PDFDocument实例
    let pdfDocument = PDFDocument(url: pdfURL)
    
    // 确保PDF文档已经加载
    guard let document = pdfDocument else {
        print("无法加载PDF文档")
        return nil
    }
    
    // 获取第一页
    let page = document.page(at: 0)
    
    // 创建图形上下文
    let rect = page?.bounds(for: .cropBox)
    UIGraphicsBeginImageContext(rect!.size)
    guard let context = UIGraphicsGetCurrentContext() else {
        return nil
    }
    
    // 渲染PDF页到图形上下文
    context.concatenate(CGAffineTransform(rotationAngle: 0))
    context.translateBy(x: 0, y: rect!.size.height);
    context.scaleBy(x: 1.0, y: -1.0);
    context.concatenate(CGAffineTransform(translationX: -rect!.origin.x, y: -rect!.origin.y));
    page?.draw(with: .cropBox, to: context)
    
    // 获取渲染完毕的图片
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return image
}

